<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\meal;

use app\admin\model\management\Lease as LeaseModel;
use app\admin\model\shop\Goods as GoodsModel;
use app\admin\model\meal\Package as PackageModel;
use app\admin\service\TriggerService;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Request;
use think\facade\Db;
/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="管理员管理")
 */
class Package extends AdminController
{

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->LeaseModel = new LeaseModel();
        $this->model  =new PackageModel();
        $this->GoodsModel=new GoodsModel();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model->where($where)->count();
            $list  = $this->model->order('id asc')->where($where)->page($page, $limit)->select();
       
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add($id = null)
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                // 'cate_id|cate_id'    => 'require|>:0',
            ];
            $post['son']=$this->getData($post);
            $this->validate($post, $rule);
               Db::startTrans();
            try {
                $save = $this->model->save($post);
                $this->model->packageAttr()->saveAll($post['son']);
                Db::commit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
    
        return $this->fetch();
    }
    public function getData($post){
        $data=[];
        if(isset($post['lease'])){
            foreach ($post['lease'] as $k => $v) {
                $data[]=[
                    'server_id'=>$k,
                    'server_type'=>2,
                    'number'=>$v
                ];
            }
        }
        if(isset($post['goods'])){
                foreach ($post['goods'] as $k => $v) {
                $data[]=[
                    'server_id'=>$k,
                    'server_type'=>3,
                    'number'=>$v
                ];
            }
        }
        return $data;
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {   
        $id  = Request::param('id');
        $row = $this->model->where('id',$id)->find();
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
           
            $rule = [];
            $this->validate($post, $rule);
          $post['son']=$this->getData($post);
               Db::startTrans();
            try {
                $save = $row->save($post);
                $row->packageAttr()->delete();
                $row->packageAttr()->saveAll($post['son']);
                Db::commit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $lease=Db::name('package_attr')->where('package_id',$id)->where('server_type',2)->select()->toArray();
        $goods=Db::name('package_attr')->where('package_id',$id)->where('server_type',3)->select()->toArray();
        $lease_arr=[];
        $goods_arr=[];
        if($lease){
            foreach ($lease as $k => $v) {
                $lease_arr[$v['server_id']]=$v['number'];
            }
            $lease_arr=json_encode($lease_arr);
        }
        if($goods){
            foreach ($goods as $k => $v) {
                $goods_arr[$v['server_id']]=$v['number'];
            }
            $goods_arr=json_encode($goods_arr);
        }

        $row['goods']=$goods_arr?$goods_arr:"";
        $row['lease']=$lease_arr?$lease_arr:"";

        $this->assign([
            'row'=>$row,
        
        ]);
       
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {  
    
        $row = $this->model->with('packageAttr')->whereIn('id', $id)->find();
     
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $this->model->whereIn('id', $id)->delete();
       
            foreach ($row as $k => $v) {
                 $main_picture=$v['main_image']?explode('|',$v['main_image']):'';
                if($main_picture){
                    foreach ($main_picture as $main) {
                        del_image($main);
                    }
                }
                $detail_picture=$v['detail_image']?explode('|',$v['detail_image']):'';
                if($detail_picture){
                    foreach ($detail_picture as $detail) {
                        del_image($detail);
                    }
                }
                del_image($v['thumb']);
            }
         
            $row->together(['packageAttr'])->delete();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * 
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
     
        $rule = [
            // 'cate_id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        // if (!in_array($post['field'], $this->allowModifyFields)) {
        //     $this->error('该字段不允许修改：' . $post['field']);
        // }
     
        $row = $this->model->where('id',$post['id'])->find();
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            // $this->error($e->getMessage());
            $this->success('保存成功');
        }
        $this->success('保存成功');
    }
     public function getLease(){
            $lease_id=input('lease_id');
            $where=[];
            if($lease_id) {
                $lease_id=str_replace('[','',$lease_id);$lease_id=str_replace(']','',$lease_id); $where=[
                ['id','in',$lease_id]
             ];
            }

            $list  = $this->LeaseModel->where($where)->field('id,title')->select();
            $data  = [
                'code'  => 1,
                'msg'   => '',
                'data'  => $list,
            ];
            return json($data);
    }
   public function getGoods(){
            $products_id=input('products_id');
            $where=[];
            if($products_id) {
                $products_id=str_replace('[','',$products_id);$products_id=str_replace(']','',$products_id); $where=[
                ['products_id','in',$products_id]
             ];
            }
            $list  = $this->GoodsModel->where($where)->field('products_id,products_title')->select();
            $data  = [
                'code'  => 1,
                'msg'   => '',
                'data'  => $list,
            ];
            return json($data);
    }
}
